package com.kob.backend.component;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.mysql.cj.xdevapi.JsonArray;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//和Controller类似,建立websocket连接
@ServerEndpoint(value="/imserver/{username}")
@Component
public class WebSocketServer {
public static  final Map<String, Session> sessionMap=new ConcurrentHashMap<>();

@OnOpen
    public void onOpen(Session session, @PathParam("username")String username){
    sessionMap.put(username,session);
    JSONObject result=new JSONObject();
    JSONArray array=new JSONArray();
    result.put("users",array);
    for(Object key:sessionMap.keySet()){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username",key);
        array.add(jsonObject);
    }
    sendAllMesssage(JSONUtil.toJsonStr(result));
}

@OnClose
public void onClose(Session session,@PathParam("username")String username){
    sessionMap.remove(username);
    JSONObject result=new JSONObject();
    JSONArray array=new JSONArray();
    result.put("users",array);
    for(Object key:sessionMap.keySet()){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username",key);
        array.add(jsonObject);
    }
    sendAllMesssage(JSONUtil.toJsonStr(result));
}

@OnMessage
public  void onMessage(String message,Session session,@PathParam("username")String username){
    JSONObject obj = JSONObject.from(JSONUtil.parseObj(message));
    String toUsername = obj.getString("to");
    String text=obj.getString("text");
    Session toSession = sessionMap.get(toUsername);
    if(toSession!=null){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("from",username);
        jsonObject.put("text",text);
        this.sendMessage(jsonObject.toString(),toSession);
    }
}

@OnError
public void onError(Session session,Throwable throwable){
    throwable.printStackTrace();
}
//发给指定ssession
private void sendMessage(String message,Session toSession){
    try{
        toSession.getBasicRemote().sendText(message);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
  //把username：session发给所有用户
    private void sendAllMesssage(String message) {
    try{
        for(Session session : sessionMap.values()){
            session.getBasicRemote().sendText(message);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    }
}
